<include file='Base:header' />
	<style>
.r_icon{
	position: absolute;
    right: 0;
    top: 0;
    width: 0;
    height: 0;
    border-top: 25px solid #ed6d3d;
    border-left: 25px solid transparent;
}
.r_icon_font{
    position: absolute;
    right: 6px;
    top: -1px;
    z-index: 999;
    color: white;
    font-weight: 600;
    font-size: 12px;
}

</style>
	<body>
		<div class="submit">
			<div id="allmap"></div>
			<h1 class="title">
				<a class="back" href="{$goback}">
					<img class="fl" src="__IMG__/back.png" style="margin-left: 5%;"/>
				</a>
				我的{$title}
				<a class="home" href="__APP__">
					<img class="fl" src="__IMG__/home_logo.png" style="margin-right: 5%;"/>
				</a>
			</h1>
			<include file='Base:_submit_intro' />
		    <form action="{:U('')}" method='post' class='ajax-form'>
		    	<input type="hidden" name='post[type]' value='{$_GET[type]}' />
		        <div class="weui-cells weui-cells_form time_input" code="time_input_0">
				    <in name="Think.get.type" value='1,2,3'>
				           <div class="weui-cell">
						        <div class="weui-cell__hd"><label for="name" class="weui-label">类型</label></div>
						        <div class="weui-cell__bd">
						          <input class="weui-input" id="vacatetype_0" code='vacate' name='post[vacate_type]' type="text" value="" readonly="" placeholder="请选择">
						        </div>
     							<span class='r_icon_font'>1</span>
								<div class='r_icon'></div>
						    </div>
				    </in>  	
		        	<php>
		        		if($_GET['year']){
			        		$date = $_GET['year'].'-'.$_GET['month'].'-'.$_GET['day'].' ';
			        		$date_end = $_GET['year'].'-'.$_GET['month'].'-'.$_GET['day'].' ';
			        		$start_time = $date.$_GET['duty_on'];
			        		$end_time = $date_end.$_GET['duty_off'];
		        		}
		        		if($_GET['type'] == 1){
		        			if($_GET['out_time']){
			        			$end_time = $_GET['out_time'];
			        		}
		        		}
		        		if($_GET['type'] == 3){
		        			if($_GET['overtime_start']){
			        			$start_time = $_GET['overtime_start'];
			        			$end_time = $_GET['overtime_end'];
			        		}
			        		if($_GET['year']){
			        			$end_time = date('Y-m-d H:i',strtotime("$end_time +1day"));
			        		}
		        		}
		        	</php>
		        		
		        		
			            <div class="weui-cell">
			                <div class="weui-cell__hd"><label class="weui-label">开始时间</label></div>
							<div class="weui-cell__bd ">
								<input class="weui-input start_input starttime" id="starttime" type="text" name='' value="{$start_time}">
							</div>
			            </div>
			            <div class="weui-cell">
			                <div class="weui-cell__hd"><label class="weui-label">结束时间</label></div>
							<div class="weui-cell__bd ">
								<input class="weui-input end_input endtime" id="endtime" type="text" placeholder="请选择" name='' value="{$end_time}">
							</div>
			           </div>
		
			        
			        	           
			        <div class="weui-cells weui-cells_form upload_img" id='upload_img_0' style='display:none'>
					  <div class="weui-cell">
					      <div class="weui-uploader">
					        <div class="weui-uploader__hd">
					          <p class="weui-uploader__title" id='img_title'>图片上传</p>
					          <!--<div class="weui-uploader__info">0/2</div>-->
					        </div>
					        <div class="weui-uploader__bd">
					          <ul class="weui-uploader__files upload_file_box" id="uploaderFilesBox_0" >
					          	<!--图片预览 -->
					          </ul>
					          <div class="weui-uploader__input-box">
					            <input id="uploaderInput_0" class="weui-uploader__input" type="file" accept="image/*" multiple="">
					          </div>
					        </div>
					      </div>
					  </div>
					</div>
					
			        <!-- <div class="weui-cells__title">{$title}事由</div> -->
			        <div class="weui-cells" style='margin-top: 0;'>
			           <div class="weui-cell">
					        <div class="weui-cell__bd">
							    <textarea class="weui-textarea ap_content" placeholder="请输入{$title}事由" rows="3" name='post[content]'></textarea>
						    </div>
					    </div>
			        </div>			        
			           
			           
		        </div>
 		        

	
		      	<div class="sumbit_btn" style="padding-bottom: 30px;">
					<input type="button" class="weui-btn weui-btn_mini weui-btn_primary" style="margin: 0 auto;" id ='add' value="+">
					<input type="button" class="weui-btn weui-btn_mini weui-btn_primary" style="margin: 0 auto;" id ='reduce' value="-">
					<input type="button" class="weui-btn weui-btn_mini weui-btn_primary ajax-submit-batch" style="margin: 0 auto;" value="提交">
				</div>
		    </form>
		</div>

		<include file='Base:footer' />
		<script src="__JS__/megapix-image.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript">
		var time_input_num = 0;//时间控件数量
		var time_input_code= 0;//时间控件累计编号
		var loading = "<i class='weui-loading'></i>";
		var issubmit = "yes";
		var post_type = "{$_GET[type]}";
		var default_time_s = '';
		var default_time_e = '';
		
		//添加按钮
		$('#add').click(function(){
 				
				time_input_num ++ ;
				time_input_code++;
				
 				var name_start = "post[start_time]_"+time_input_code;
 				var name_end = "post[end_time]_"+time_input_code;
				var date_obj = $('.time_input:last').clone();
				
				var input_id_vacatetype = "vacatetype_"+time_input_code;
				
				date_obj.find('.starttime').attr('name',name_start);
				date_obj.find('.endtime').attr('name',name_end);
				date_obj.attr('code',"time_input_"+time_input_code);
				date_obj.find('.r_icon_font').text(time_input_code+1);
				date_obj.find("input[code='vacate']").attr('id',input_id_vacatetype);
				date_obj.find(".vacatetype_value").attr('name',input_id_vacatetype);
				date_obj.find("input[type='file']").attr('id',"uploaderInput_"+time_input_code);
				date_obj.find(".upload_img").attr('id','upload_img_'+time_input_code);
				date_obj.find(".upload_file_box").attr('id','uploaderFilesBox_'+time_input_code);
				
				date_obj.find("#uploaderFilesBox_"+time_input_code).empty();
				
				
				$('.time_input:last').after(date_obj);
				
				add_datetime();
				init_select_vacatetype(time_input_code)
				init_input_img(time_input_code);
			}) 
			
		//减少按钮
		$('#reduce').click(function(){
			if (time_input_num >= 1){
				reduce_datepick();
			}
		})
			
			
			
		//提交按钮	
		$(".ajax-submit-batch").click(function() {
			
				//提交出现加载
				$(".ajax-submit").hide();
				$(".sumbit_btn").append(loading);
				var ajaxForm = $('form.ajax-form');
				var _url = ajaxForm.attr('action');
				$(".login_btn").append(loading);
				
				if(issubmit == "yes"){
					issubmit = "no";
					var imgbox_ary = [];
					var date_obj = [];
				//	var submit_data = ajaxForm.serializeArray();
					//获取时间集合
					$('.time_input').each(function(index){
						date_obj[index] = {};
						date_obj[index].starttime = $(this).find('.starttime').val()
						date_obj[index].endtime = $(this).find('.endtime').val();
						date_obj[index].code = $(this).attr('code');
						date_obj[index].vacate_type = $(this).find('input[code="vacate"]').attr('data-values');
						date_obj[index].content = $(this).find('.ap_content').val();
						
						//收集图片素材,获取二进制数据流
						var imgbox = $(this).find('.avatar_preview');
						if (imgbox.length > 0){
							imgbox.each(function(img_index){
								imgbox_ary[img_index] = $(this).attr('src')
							})
							
							date_obj[index].img = imgbox_ary;
						}
						
					})
					
					var submit_len = date_obj.length;
					var submit_succ = 0;
					var alert_msg = '';
					//循环发送请求
					for(i=0;i<submit_len;i++){
						if (date_obj[i] == undefined) {
							continue;
						}
						var code_num_str = date_obj[i].code.substring(11);//第几个编号
						var code_num = parseInt(code_num_str)+1;
						var submit_data={
								'post[start_time]':date_obj[i].starttime,
								'post[end_time]':date_obj[i].endtime,
								'post[type]':post_type,
								'post[vacate_type]':date_obj[i].vacate_type,
								'post[content]':date_obj[i].content,
								'post[resaon_img]':date_obj[i].img,
						};
						
						
						//console.log(submit_data)
						var ret = ajax_submit(_url,submit_data);
 						if (ret.status == undefined) return false;
						
						if (ret.status == false){
			
							$(".sumbit_btn .weui-loading").hide();
							$(".ajax-submit").show();
							if (submit_succ >= 1){
								alert_msg = "已成功提交["+submit_succ+"]条申请,申请编号["+code_num+"]提交失败:"+ret.info;
							}else{
								alert_msg = "申请编号["+code_num+"]:"+ret.info;
							}
								
							
							$.alert(alert_msg);
							issubmit = 'yes';
							return false;
						}else{
							//执行成功的
							reduce_datepick(date_obj[i].code); //减少视觉时间控件
							delete date_obj[i]; //移除时间累计对象
							submit_succ ++ ;
						} 
						
					}
					
  					$.toast(ret.info);
			 		setTimeout(function() {
						if(ret.url) {
							location.href = ret.url;
						} else {
							location.reload();
						}
					}, 2000);   
				}
			})
		//发送ajax数据
		function ajax_submit(_url,_data){
			var result;
			$.ajax({
				type: 'post',
				url: _url,
				data: _data,
				async:false,
				success: function(ret) {
						result =  ret;
				}
			});
			
			return result;
		}		
		
		//减少移除时间控件数量
		function reduce_datepick(_code){
			if (_code) {
				
				$(".time_input[code='"+_code+"']").remove();
			}else{
				$(".time_input:last").remove();
			}
			
			time_input_num -- ;//减少页面控件数量
			
		}
		
		//初始化图片选择器
		init_input_img(0);
		function init_input_img(_id){
				var class_upload_input = 'uploaderInput_'+_id;  //文件上传，input框class名
				var class_file_box = 'uploaderFilesBox_'+_id;
				
				var i = 0;
				var fileInput = document.getElementById(class_upload_input);
				
				
				fileInput.onchange = function() {
					var thumb_id = 'thumb_'+_id+'_'+i;
					var li_id = 'li_'+_id+'_'+i;
				   var file = fileInput.files[0];
				   // MegaPixImage constructor accepts File/Blob object.
				   var mpImg = new MegaPixImage(file);
				   var img_li= '<li class="weui-uploader__file" id='+li_id+' onclick="javascript:delete_preview_img(this)">'
				            	+   '<img class="avatar_preview" id="'+thumb_id+'" src="" style="width: 100%;height: 100%;"/>'
					            +	'<input class="" type="hidden" name="post[resaon_img][]" value="" />'
					           	+'</li>';
					$('#'+class_file_box).append(img_li);   
					
					var resImg = document.getElementById(thumb_id);
					mpImg.render(resImg); 
					i++;
					console.log(i)
				 };
				
		}
		
		//删除预览图
		function delete_preview_img(_this){
			var target = _this.id;
 			$.confirm("是否删除图片？", function() {
				  //点击确认后的回调函数
 					$('#'+target).remove();
				  }, function() {
				  //点击取消后的回调函数
				  }); 
		}
	       
			function GetArgsFromHref(sHref, sArgName){
			      var args    = sHref.split("?");
			      var retval = "";
			    
			      if(args[0] == sHref) /*参数为空*/
			      {
			           return retval; /*无需做任何处理*/
			      }  
			      var str = args[1];
			      args = str.split("&");
			      for(var i = 0; i < args.length; i ++)
			      {
			          str = args[i];
			          var arg = str.split("=");
			          if(arg.length <= 1) continue;
			          if(arg[0] == sArgName) retval = arg[1]; 
			      }
			      return retval;
			}
	       	
	       	
	       	var duty_on = GetArgsFromHref(window.location.href,'duty_on');
	       	var type = GetArgsFromHref(window.location.href,'type');
			if(duty_on == ""){
				//input 默认当前时间
				//当前时间
				var time = new Date();
				var now_y = time.getFullYear();
				var now_m = time.getMonth()+1;
				var now_d = time.getDate();
				var now_h = time.getHours();
				var now_min = time.getMinutes();
				var buling = function(a){
					if(a<10){
						return "0" + a;
					}else{
						return a;
					}
				}
				now_m = buling(now_m)
				now_d= buling(now_d)
				overtime_end_d = buling(parseInt(now_d)+1)
				now_h = buling(now_h)
				now_min= buling(now_min)
				var now_time = now_y+"-"+now_m+"-"+now_d+" "+now_h+":"+now_min;
				var duty_time = now_y+"-"+now_m+"-"+now_d+" "+"18:00";
				var overtime_start = now_y+"-"+now_m+"-"+now_d+" "+"20:00";
				var overtime_end = now_y+"-"+now_m+"-"+overtime_end_d+" "+"05:59";

				$(".starttime").attr("value",now_time);
				$(".endtime").attr("value",now_time);
				if(type == "1"){
					$(".endtime").attr("value",duty_time);
				}else if(type == "3"){
 					$(".starttime").attr("value",overtime_start);
					$(".endtime").attr("value",overtime_end); 
				}else{
					$(".starttime").attr("value",now_y+"-"+now_m+"-"+now_d+" "+"09:00");
					$(".endtime").attr("value",duty_time);
				}
			}
			
			//初始化 假期选择器
			init_select_vacatetype(0)
			
			
			//假期类型选择器
			function init_select_vacatetype(_id){
				var _sick_type = ['104','109','110','200','201']; //带薪病假类型
				var _vacateType = '{$vacate_type_json}'; //全部假期类型数据
				var $this = 'vacatetype_'+_id
				
				$this = $("#"+$this);
				if (_vacateType) {
					$this.select({
					  title: "选择请假类型",
					  items: JSON.parse(_vacateType),
					  onChange:function(e){
						  
							default_time_s = $('#starttime').val();
							default_time_e = $('#endtime').val();
						  
						  if (e.values == '301') {
							  var s_date = default_time_s.split(' ');
							  add_datetime();
							  $('.starttime').attr('value',s_date[0]+' 09:00')
							  $('.endtime').attr('value',s_date[0]+' 18:00')
							  $('.weui-media-box__title').text('若公休日在公司加班，点击提交加班申请选择开始时间和结束时间，确认无误后点击提交，若提交错误可左滑撤回。');
						  }
						  if (e.values == '300') {
							  $('.starttime').attr('value',default_time_s)
							  $('.endtime').attr('value',default_time_e)
							  $('.weui-media-box__title').text('若加班时间未超过凌晨6:00，则无需申请。若超过凌晨6:00，点击提交加班申请选择开始时间和结束时间，确认无误后点击提交，若提交错误可左滑撤回。 ');
						  }
						  
						  
						  
						  if (e.values == 111 || _sick_type.indexOf(e.values) >= 0 ) {
							  //病假
							  $('#upload_img_'+_id).show();
							  $('#img_title').text('图片上传')
							  if (e.values == '201') $('#img_title').text('OA截图上传')
							  if (e.values == '200') $('#img_title').text('相关证明')
						  }else{
							  $('#upload_img_'+_id).hide();
						  } 
						  
						  return false;
					  }
					});
				}				
			}
			
			//请事假的时候，提醒请年假
			function confirmAnnual(val){
				var annual_days = Number("{$att_info.annual}");
				if (annual_days > 0 && val==102) {
					$.confirm({
						  title: '确定要请事假？',
						  text: '亲，您还有'+annual_days+'天年假，要不请个年假吧？',
						  onOK: function () {
						    //点击确认
							  $('#vacatetype_value').val(103);
						      $('#vacatetype').val('年假');	
						      $('#vacatetype').attr('data-values','103');	
						    return false;
						  },
						  onCancel: function () {
						  }
						});
					return true;
				}
				return false;
			}
			//外出功能才需要获取定位
/* 			if ("{$_GET['type']}" == 1) {
				
				// 百度地图API功能
				var map = new BMap.Map("allmap");
				var point = new BMap.Point(116.331398,39.897445)
				map.centerAndZoom(point,12);
				var geoc = new BMap.Geocoder();    
			
			
				var geolocation = new BMap.Geolocation();
				geolocation.getCurrentPosition(function(r){
					if(this.getStatus() == BMAP_STATUS_SUCCESS){
						var mk = new BMap.Marker(r.point);
						map.addOverlay(mk);
						map.panTo(r.point);
						var pt = r.point;
						geoc.getLocation(pt, function(rs){
							var addComp = rs.addressComponents;
							$(".map").attr("value",rs.address);
						});     
					}
					else {
						alert('failed'+this.getStatus());
					}        
				},{enableHighAccuracy: true})
			} */
			
			//设置时间选择器
			
			//当前时间
			var time = new Date();
			var now_y = time.getFullYear();
			var now_m = time.getMonth()+1;
			var now_d = time.getDate();
			var min_y = time.getFullYear()-1;
			var max_y = time.getFullYear()+1;
			var buling = function(a){
				if(a<10){
					return "0" + a;
				}else{
					return a;
				}
			}
			now_m = buling(now_m);
			now_d= buling(now_d);
			var min_day = min_y + "-01-01";
			var max_day = max_y + "-"+now_m+"-"+now_d;
			
			add_datetime();
			function add_datetime(){
				
				$(".starttime").datetimePicker({
					yearSplit: "-",
					monthSplit: "-",
					dateSplit: "",
					min: min_day,
					max: max_day,
				});
				$(".endtime").datetimePicker({
					yearSplit: "-",
					monthSplit: "-",
					dateSplit: "",
					min: min_day,
					max: max_day,
				});				
				
			}
			

			
			
			
		</script>
	</body>
</html>